package tp.tecnicasdisenio.dao.impl.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;

import tp.tecnicasdisenio.dao.DaoException;
import tp.tecnicasdisenio.dao.MateriaDaoInterface;
import tp.tecnicasdisenio.model.entity.Cuatrimestre;
import tp.tecnicasdisenio.model.entity.Materia;

public class MateriaDao extends DaoAbstract implements MateriaDaoInterface{

	private String nombreTabla = "materias", atributoId = "codigo_materia";
	
	private static MateriaDao instancia = null; 
	
	private MateriaDao(){}
	
	public static MateriaDao getInstance(){
		if (instancia == null)
			instancia = new MateriaDao();
		return instancia;
	}
	
	private ArrayList<Materia> obtenerMateria(String id, boolean unoSolo) {
		ArrayList<Materia> resultado = null;
		
		try {
			String queryString = "SELECT * FROM " + this.nombreTabla;
			
			if (unoSolo)
				queryString = queryString.concat(" WHERE " + this.atributoId + "=?");

			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			if (unoSolo)
				preparedStatement.setString(1, id);
			
			resultSet = preparedStatement.executeQuery();
			
			resultado = new ArrayList<Materia>();
			Materia materiaDB = null;
			
			while (resultSet.next()) {
				materiaDB = new Materia();
				materiaDB.setCodigo(resultSet.getString("codigo_materia"));
				materiaDB.setNombre(resultSet.getString("nombre"));
				materiaDB.setEmail(resultSet.getString("email"));
				materiaDB.setPassword(resultSet.getString("password"));
				materiaDB.setHost(resultSet.getString("host"));
				materiaDB.setSmtpHost(resultSet.getString("smtp_host"));
				materiaDB.setSmtpPort(resultSet.getString("smtp_port"));
				
				resultado.add(materiaDB);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultado;
	}
	
	@Override
	public Materia getPorId(String id) {
		ArrayList<Materia> listaMaterias = this.obtenerMateria(id, true);
		Materia materia = null;
		if (!listaMaterias.isEmpty())
			materia = listaMaterias.iterator().next();
		
		return materia;
	}

	@Override
	public ArrayList<Materia> obtenerTodos() {
		return (this.obtenerMateria(null, false));
	}

	@Override
	public void borrar(Materia entidad) {
		try {
			String queryString = "DELETE FROM " + this.nombreTabla + " WHERE " + this.atributoId + "=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, entidad.getCodigo());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void actualizar(Materia entidad) {
		try {
			String queryString = "UPDATE " + this.nombreTabla + " SET nombre=?, email=?, password=?, host=?, smtp_host=?, smtp_port=? WHERE " + this.atributoId + "=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, entidad.getNombre());
			preparedStatement.setString(2, entidad.getEmail());
			preparedStatement.setString(3, entidad.getPassword());
			preparedStatement.setString(4, entidad.getHost());
			preparedStatement.setString(5, entidad.getSmtpHost());
			preparedStatement.setString(6, entidad.getSmtpPort());			
			preparedStatement.setString(7, entidad.getCodigo());

			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void insertar(Materia entidad) {
		try {
			String queryString = "INSERT INTO " + this.nombreTabla + "(codigo_materia, nombre, email, password, host, smtp_host, smtp_port) VALUES(?,?,?,?,?,?,?)";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, entidad.getCodigo());
			preparedStatement.setString(2, entidad.getNombre());
			preparedStatement.setString(3, entidad.getEmail());
			preparedStatement.setString(4, entidad.getPassword());
			preparedStatement.setString(5, entidad.getHost());
			preparedStatement.setString(6, entidad.getSmtpHost());
			preparedStatement.setString(7, entidad.getSmtpPort());
			
			preparedStatement.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean existe(Materia materia) {
		boolean resultado = false;
		
		if (materia != null) {
			Materia materiaBD = this.getPorId(materia.getCodigo());
			
			if ((materiaBD != null) && (materia.getNombre().compareTo(materiaBD.getNombre()) == 0)) 
				resultado = true;
					
		}
		return resultado;
	}

	@Override
	public Materia getPorEmail(String email) {
		Materia materia = null;
		try {
			String queryString = "SELECT * FROM " + this.nombreTabla + " WHERE email=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, email);
			
			resultSet = preparedStatement.executeQuery();
			
			if (resultSet.next()) {
				materia = new Materia();
				materia.setCodigo(resultSet.getString("codigo_materia"));
				materia.setNombre(resultSet.getString("nombre"));
				materia.setEmail(resultSet.getString("email"));
				materia.setPassword(resultSet.getString("password"));
				materia.setHost(resultSet.getString("host"));
				materia.setSmtpHost(resultSet.getString("smtp_host"));
				materia.setSmtpPort(resultSet.getString("smtp_port"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return materia;
	}

	private ArrayList<String> obtenerEmails(String codigoMateria, Cuatrimestre cuatrimestre, boolean docentes) {
		ArrayList<String> resultado = new ArrayList<String>();
		
		try {
			String queryString = "SELECT email FROM ";
			
			if (docentes)
				queryString = queryString.concat("docentes WHERE codigo_materia=?");
			else
				queryString = queryString.concat("alumnos WHERE alumnos.padron IN (SELECT cursa.padron FROM cursa" +
						" WHERE codigo_materia=? AND cuatrimestre=? AND anio=?)");

			connection = this.getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, codigoMateria);

			if (!docentes){
				preparedStatement.setInt(2, new Integer(cuatrimestre.getCuatrimestre()));
				preparedStatement.setInt(3, cuatrimestre.getAnio());
			}
			
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				resultado.add(resultSet.getString("email"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultado;
	}
	
	@Override
	public ArrayList<String> getEmailsDocentes(String codigoMateria) {
		return (this.obtenerEmails(codigoMateria, null, true));
	}

	@Override
	public ArrayList<String> getEmailsAlumnos(String codigoMateria,	Cuatrimestre cuatrimestre) {
		return (this.obtenerEmails(codigoMateria, cuatrimestre, false));
	}

	@Override
	public void inscribirDocente(String codigoMateria, String email, String nombre) {
		try {
			String queryString = "INSERT INTO docentes (codigo_materia, email, nombre) VALUES(?,?,?)";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, codigoMateria);
			preparedStatement.setString(2, email);
			preparedStatement.setString(3, nombre);
			
			preparedStatement.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public int getUltimoNroGrupoRegistrado(Materia materia, Cuatrimestre cuatrimestre) {
		int  resultado = 0;
		try {
			String queryString = "SELECT MAX(nro_grupo) FROM grupos WHERE codigo_materia=? AND cuatrimestre=? AND anio=?";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setString(1, materia.getCodigo());
			preparedStatement.setInt(2, new Integer(cuatrimestre.getCuatrimestre()));
			preparedStatement.setInt(3, cuatrimestre.getAnio());
			
			resultSet = preparedStatement.executeQuery();
			
			if (resultSet.next()) {
				resultado = resultSet.getInt("MAX(nro_grupo)");
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultado;
	}

	@Override
	public ArrayList<Materia> filtrarMaterias(String codigoMateria,
			String nombre, String email) {

		ArrayList<Materia> listaMaterias = new ArrayList<Materia>();
		try {
			codigoMateria = codigoMateria.toUpperCase();
			nombre = nombre.toUpperCase();
			email = email.toUpperCase();
			
			String queryString = "SELECT * FROM materias WHERE UPPER(codigo_materia) LIKE '%" + codigoMateria + "%' " +
					"AND UPPER(nombre) LIKE '%" + nombre + "%' AND UPPER(email) LIKE '%" + email + "%'";
			connection = getConnection();
			preparedStatement = connection.prepareStatement(queryString);
			
			resultSet = preparedStatement.executeQuery();
			
			Materia materiaBD = null;
			while (resultSet.next()) {
				materiaBD = new Materia();
				materiaBD.setCodigo(resultSet.getString("codigo_materia"));
				materiaBD.setNombre(resultSet.getString("nombre"));
				materiaBD.setEmail(resultSet.getString("email"));
				materiaBD.setPassword(resultSet.getString("password"));
				materiaBD.setHost(resultSet.getString("host"));
				materiaBD.setSmtpHost(resultSet.getString("smtp_host"));
				materiaBD.setSmtpPort(resultSet.getString("smtp_port"));
				
				listaMaterias.add(materiaBD);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw (new DaoException(e));
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return listaMaterias;
	}
}
